package auth

import (
	"client2/tmp/zkp"
	"time"

	"github.com/google/uuid"
)

// VerifyRequest 验证请求结构
type VerifyRequest struct {
	DeviceID    string `json:"device_id"`
	ChallengeID string `json:"challenge_id"`
	Proof       struct {
		Proof         string                 `json:"proof"`
		PublicWitness map[string]interface{} `json:"public_witness"`
	} `json:"proof"`
}

// VerifyResponse 验证响应结构
type VerifyResponse struct {
	Success   bool      `json:"success"`
	SessionID string    `json:"session_id,omitempty"`
	Token     string    `json:"token,omitempty"`
	ExpiresAt time.Time `json:"expires_at,omitempty"`
	Message   string    `json:"message,omitempty"`
	Error     string    `json:"error,omitempty"`
}

// Verifier 处理证明验证
type Verifier struct {
	challengeStore *ChallengeStore
	keyManager     *zkp.KeyManager
}

// NewVerifier 创建新的验证器
func NewVerifier(challengeStore *ChallengeStore, keyManager *zkp.KeyManager) *Verifier {
	return &Verifier{
		challengeStore: challengeStore,
		keyManager:     keyManager,
	}
}

// VerifyProof 验证零知识证明
func (v *Verifier) VerifyProof(req VerifyRequest) (*VerifyResponse, error) {
	// 获取挑战信息
	challenge, exists := v.challengeStore.GetChallenge(req.ChallengeID)
	if !exists {
		return &VerifyResponse{
			Success: false,
			Error:   "INVALID_CHALLENGE",
			Message: "无效或过期的挑战ID",
		}, nil
	}

	// 检查设备ID是否匹配
	if req.DeviceID != challenge.DeviceID {
		return &VerifyResponse{
			Success: false,
			Error:   "DEVICE_MISMATCH",
			Message: "设备ID不匹配",
		}, nil
	}

	// 获取验证密钥
	vk := v.keyManager.GetVerifyingKey()

	// 验证证明
	valid, err := zkp.VerifyProof(vk, req.Proof.Proof, req.Proof.PublicWitness)
	if err != nil {
		return &VerifyResponse{
			Success: false,
			Error:   "PROOF_VALIDATION_ERROR",
			Message: "证明验证错误: " + err.Error(),
		}, nil
	}

	if !valid {
		return &VerifyResponse{
			Success: false,
			Error:   "INVALID_PROOF",
			Message: "无效的零知识证明",
		}, nil
	}

	// 验证成功，移除挑战
	v.challengeStore.RemoveChallenge(req.ChallengeID)

	// 生成会话ID和令牌
	sessionID := uuid.New().String()
	token := generateJWTToken(req.DeviceID, sessionID)

	return &VerifyResponse{
		Success:   true,
		SessionID: sessionID,
		Token:     token,
		ExpiresAt: time.Now().Add(1 * time.Hour),
		Message:   "认证成功",
	}, nil
}

// generateJWTToken 生成JWT令牌（简化实现）
func generateJWTToken(deviceID, sessionID string) string {
	// 实际实现应使用JWT库生成签名令牌
	// 这里返回简化版本
	return "jwt." + deviceID + "." + sessionID
}
